﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StockAna
{
    class Config
    {
        public static Config inst;

        public SQLiteConnection dbconn { get; private set; }

        public Config()
        {
            inst = this;

            dbconn = new SQLiteConnection("Data Source =" + Environment.CurrentDirectory + "\\data.db");
            dbconn.Open();

            RunSql("CREATE TABLE IF NOT EXISTS rates(id INTEGER, rate REAL);");
            RunSql("CREATE TABLE IF NOT EXISTS stock_prizes(code CHAR(10) PRIMARY KEY, prize REAL);");
            RunSql(@"CREATE TABLE IF NOT EXISTS stock_safes(
code CHAR(10) PRIMARY KEY, 
profit0 REAL, 
profit_rate REAL, 
float_asset REAL, 
float_debt REAL, 
depreciation REAL,
pay REAL,
capital REAL,
bonus REAL,
refix REAL,
safe_rate REAL,
name CHAR(32),
note TEXT
);");
            RunSql("CREATE TABLE IF NOT EXISTS migrate(id INTEGER);");
            MigrateSql(1, "ALTER TABLE stock_prizes ADD COLUMN name CHAR(32);");
        }

        public static void RunSql(string sql)
        {
            SQLiteCommand c1 = new SQLiteCommand(sql, Config.inst.dbconn);
            c1.ExecuteNonQuery();
        }

        public static SQLiteDataReader ReadSql(string sql)
        {
            SQLiteCommand q1 = new SQLiteCommand(sql, Config.inst.dbconn);
            return q1.ExecuteReader();
        }

        private void MigrateSql(int idx, string sql)
        {
            int lastIdx = 0;
            bool firstMigrate = true;
            SQLiteDataReader reader = ReadSql("SELECT * FROM migrate LIMIT 1;");
            if (reader.Read())
            {
                lastIdx = reader.GetInt32(0);
                firstMigrate = false;
            }

            if (idx > lastIdx)
            {
                RunSql(sql);
                if (firstMigrate)
                {
                    RunSql(string.Format("INSERT INTO migrate VALUES({0});", idx));
                }
                else
                {
                    RunSql(string.Format("UPDATE migrate SET id={0};", idx));
                }
                
            }
        }
    }
}
